package co.za.itweb.itweblite;

import java.net.URL;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.GradientDrawable;
import android.graphics.drawable.GradientDrawable.Orientation;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.KeyEvent;



public class ItWebLiteActivity extends FragmentActivity {
	
	
	RefreshTask rt;
	int max;
	ProgressDialog progressDialog;

	@Override
	public void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);
		setContentView(R.layout.start);
		
		int colors[] = { Color.parseColor("#FFea1c23"),
				Color.parseColor("#FFa00d10") };
		GradientDrawable grad = new GradientDrawable(Orientation.TOP_BOTTOM,
				colors);
		this.getWindow().setBackgroundDrawable(grad);

		if (internetConnection()) {
		
					rt = new RefreshTask(this);
					if (rt.getStatus() == AsyncTask.Status.PENDING) {
						// My AsyncTask has not started yet
						rt.execute();
					}

					if (rt.getStatus() == AsyncTask.Status.RUNNING) {
						// My AsyncTask is currently doing work in doInBackground()
					}

					if (rt.getStatus() == AsyncTask.Status.FINISHED) {
						// My AsyncTask is done and onPostExecute was called

					}
           

			
				
		} else {
			AlertDialog.Builder builder = new AlertDialog.Builder(this);
			builder.setMessage("There is no internet connection.Please connect to the internet and try again.")
			       .setCancelable(false)
			       .setPositiveButton("OK", new DialogInterface.OnClickListener() {
			           public void onClick(DialogInterface dialog, int id) {
			        	
			        	  dialog.cancel();
			   	    	finish();
			           }
			       
			       
			       });
			AlertDialog alert = builder.create();
			alert.show();
			
		}

	}



	public boolean internetConnection() {
		ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo info = connMgr.getActiveNetworkInfo();

		return (info != null && info.isConnected());

	}

	
	
	private class RefreshTask extends AsyncTask<Void, Integer, Void> {
		private SaundProgressBar m_regularProgressBar;
		RSSFeed feed;
		
		

		public RefreshTask(ItWebLiteActivity activity) {
			
			
			m_regularProgressBar = (SaundProgressBar) findViewById(R.id.regularprogressbar);

		}

		protected void onPreExecute() {
			Drawable indicator = getResources().getDrawable(
					R.drawable.progress_indicator);
			Rect bounds = new Rect(0, 0, indicator.getIntrinsicWidth() + 5,
					indicator.getIntrinsicHeight());

			indicator.setBounds(bounds);
			this.m_regularProgressBar.setProgressIndicator(indicator);

		}

		@Override
		protected Void doInBackground(Void... params) {

			for (int o = 0; o < FirstScreen.feeds.length; o++) {
				feed = getFeed(FirstScreen.feeds[o]);

				if (feed != null) {
					FirstScreen.fList.add(feed);
					
					int x = o * (100 / FirstScreen.feeds.length);
					publishProgress(x);
					if (isCancelled()) {
						
						
						FirstScreen.fList.clear();
						m_regularProgressBar.setProgress(0);
						m_regularProgressBar.destroyDrawingCache();
						Intent returnIntent = new Intent();
						returnIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
						setResult(RESULT_CANCELED,returnIntent);
						finish();
						

						return null;
					}

				}

			}

			return null;
		}

		@Override
		protected void onProgressUpdate(Integer... values) {
			this.m_regularProgressBar.setProgress(values[0]);

		}

		@Override
		protected void onPostExecute(Void result) {
			
			if(FirstScreen.fList.size()>1){
			
			Intent returnIntent = new Intent();
			
			setResult(RESULT_OK, returnIntent);
			returnIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
			finish();
			}else{
				Intent returnIntent = new Intent();
				returnIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
				setResult(RESULT_CANCELED,returnIntent);
				finish();
			}

		}
	}

	

	public static RSSFeed getFeed(String urlToRssFeed) {
		try {

			URL url = new URL(urlToRssFeed);

			SAXParserFactory factory = SAXParserFactory.newInstance();
			factory.setNamespaceAware(true);

			SAXParser parser = factory.newSAXParser();

			XMLReader xmlreader = parser.getXMLReader();

			RSSHandler theRssHandler = new RSSHandler();

			xmlreader.setContentHandler(theRssHandler);

			InputSource is = new InputSource(url.openStream());

			xmlreader.parse(is);

			
			return theRssHandler.getFeed();
		} catch (Exception ee) {
			System.out.println(ee.toString()+"~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
			return null;
		}
	}
	
	
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event)
	{
	    if ((keyCode == KeyEvent.KEYCODE_HOME))
	    {
	    	
	    	
	    	if (rt.getStatus() == AsyncTask.Status.RUNNING) {
	    		
				rt.m_regularProgressBar.setProgress(0);
				rt.cancel(true);
			}
	    	Intent returnIntent = new Intent();
	    	returnIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
	    	setResult(RESULT_CANCELED,returnIntent);
	    	
	    	finish();
	    	
	    }
	    if ((keyCode == KeyEvent.KEYCODE_BACK)){
	    	
	    	if (rt.getStatus() == AsyncTask.Status.RUNNING) {
	    		
			
				rt.cancel(true);
			}
	    	Intent returnIntent = new Intent();
	    	returnIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
	    	setResult(RESULT_CANCELED,returnIntent);
	    	finish();
	    	
	    	
	    }
	    
	  
	    return super.onKeyDown(keyCode, event);
	}
	
	@Override
	public void onBackPressed() {
		if (rt.getStatus() == AsyncTask.Status.RUNNING) {
    	
			
			rt.cancel(true);
		}
		
		Intent returnIntent = new Intent();
		returnIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
		setResult(RESULT_CANCELED,returnIntent);
    	
    	finish();
	return;
	}
	
	
	

}